{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Computation graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MulLayer:\n",
    "    def __init__(self):\n",
    "        self.x = None\n",
    "        self.y = None\n",
    "    \n",
    "    def forward(self, x, y):\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "        out = x * y\n",
    "        return out\n",
    "    \n",
    "    def backward(self, dout):\n",
    "        dx = dout * self.y\n",
    "        dy = dout * self.x\n",
    "        return dx, dy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "apple = 100\n",
    "apple_num = 2\n",
    "tax = 1.1\n",
    "\n",
    "# layer\n",
    "mul_apple_layer = MulLayer()\n",
    "mul_tax_layer = MulLayer()\n",
    "\n",
    "# forward\n",
    "apple_price = mul_apple_layer.forward(apple, apple_num)\n",
    "price = mul_tax_layer.forward(apple_price, tax)\n",
    "\n",
    "print(price)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# backward\n",
    "dprice = 1\n",
    "dapple_price, dtax = mul_tax_layer.backward(dprice)\n",
    "dapple, dapple_num = mul_apple_layer.backward(dapple_price)\n",
    "\n",
    "print(dapple, dapple_num, dtax)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class AddLayer:\n",
    "    def __init__(self):\n",
    "        pass\n",
    "    \n",
    "    def forward(self, x, y):\n",
    "        out = x + y\n",
    "        return out\n",
    "    \n",
    "    def backward(self, dout):\n",
    "        dx = dout * 1\n",
    "        dy = dout * 1\n",
    "        return dx, dy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "apple = 100\n",
    "apple_num = 2\n",
    "orange = 150\n",
    "orange_num = 3\n",
    "tax = 1.1\n",
    "\n",
    "# layer\n",
    "mul_apple_layer = MulLayer()\n",
    "mul_orange_layer = MulLayer()\n",
    "add_apple_orange = AddLayer()\n",
    "mul_tax_layer = MulLayer()\n",
    "\n",
    "# forward\n",
    "apple_price = mul_apple_layer.forward(apple, apple_num)\n",
    "orange_price = mul_orange_layer.forward(orange, orange_num)\n",
    "all_price = add_apple_orange.forward(apple_price, orange_price)\n",
    "price = mul_tax_layer.forward(all_price, tax)\n",
    "\n",
    "# backward\n",
    "dprice = 1\n",
    "dall_price, dtax = mul_tax_layer.backward(dprice)\n",
    "dapple_price, dorange_price = add_apple_orange.backward(dall_price)\n",
    "dorange, dorange_num = mul_orange_layer.backward(dorange_price)\n",
    "dapple, dapple_num = mul_apple_layer.backward(dapple_price)\n",
    "\n",
    "print(f\"{price:.2f}\")\n",
    "print(f\"{dapple_num:.2f}, {dapple:.2f}, {dorange:.2f}, {dorange_num:.2f}, {dtax:.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Impremention of activation function layer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Relu:\n",
    "    def __init__(self):\n",
    "        self.mask = None\n",
    "    \n",
    "    def forward(self, x):\n",
    "        self.mask = (x <= 0)\n",
    "        out = x.copy()\n",
    "        out[self.mask] = 0\n",
    "        return out\n",
    "    \n",
    "    def backward(self, dout):\n",
    "        dout[self.mask] = 0\n",
    "        dx = dout\n",
    "        return dx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "def diff(f, x):\n",
    "    h = 1e-4\n",
    "    return (f(x+h) - f(x-h)) / (2*h)\n",
    "\n",
    "x = np.arange(-10, 10, 0.01)\n",
    "y = diff(np.exp, x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.plot(x, np.exp(x), color=\"Black\", linewidth=3)\n",
    "plt.plot(x, y, color=\"Yellow\", linestyle=\"dashed\")\n",
    "plt.xlim(-10, 10)\n",
    "plt.ylim(0, 100)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Sigmoid:\n",
    "    def __init__(self):\n",
    "        self.out = None\n",
    "        \n",
    "    def forward(self, x):\n",
    "        out = 1 / (1 + np.exp(-x))\n",
    "        self.out = out\n",
    "        return out\n",
    "    \n",
    "    def backward(self, dout):\n",
    "        dx = dout * (1.0 - self.out) * self.out\n",
    "        return dx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Affine/Softmax Layer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Affine:\n",
    "    def __init__(self, W, b):\n",
    "        self.W = W\n",
    "        self.b = b\n",
    "        self.x = None\n",
    "        self.dW = None\n",
    "        self.db = None\n",
    "    \n",
    "    def forward(self, x):\n",
    "        self.x = x\n",
    "        out = np.dot(x, self.W) + self.b\n",
    "        return out\n",
    "    \n",
    "    def backward(self, dout):\n",
    "        dx = np.dot(dout, self.W.T)\n",
    "        self.dW = np.dot(self.x.T, dout)\n",
    "        self.db = np.sum(dout, axis=0)\n",
    "        return dx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from deep_learning_from_scratch.common.functions import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SoftmaxWithLoss:\n",
    "    def __init__(self):\n",
    "        self.loss = None\n",
    "        self.y = None\n",
    "        self.t = None\n",
    "        \n",
    "    def forward(self, x, t):\n",
    "        self.t = t\n",
    "        self.y = softmax(x)\n",
    "        self.loss = cross_entropy_error(self.y, self.t)\n",
    "    \n",
    "    def backward(self, dout=1):\n",
    "        batch_size = self.t.shape[0]\n",
    "        dx = (self.y - self.t) / batch_size\n",
    "        return dx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imprementation of Neural Network with Backpropagation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from deep_learning_from_scratch.common.functions import *\n",
    "from deep_learning_from_scratch.common.util import im2col, col2im\n",
    "\n",
    "\n",
    "class Relu:\n",
    "    def __init__(self):\n",
    "        self.mask = None\n",
    "\n",
    "    def forward(self, x):\n",
    "        self.mask = (x <= 0)\n",
    "        out = x.copy()\n",
    "        out[self.mask] = 0\n",
    "\n",
    "        return out\n",
    "\n",
    "    def backward(self, dout):\n",
    "        dout[self.mask] = 0\n",
    "        dx = dout\n",
    "\n",
    "        return dx\n",
    "\n",
    "\n",
    "class Sigmoid:\n",
    "    def __init__(self):\n",
    "        self.out = None\n",
    "\n",
    "    def forward(self, x):\n",
    "        out = sigmoid(x)\n",
    "        self.out = out\n",
    "        return out\n",
    "\n",
    "    def backward(self, dout):\n",
    "        dx = dout * (1.0 - self.out) * self.out\n",
    "\n",
    "        return dx\n",
    "\n",
    "\n",
    "class Affine:\n",
    "    def __init__(self, W, b):\n",
    "        self.W =W\n",
    "        self.b = b\n",
    "        \n",
    "        self.x = None\n",
    "        self.original_x_shape = None\n",
    "        # 重み・バイアスパラメータの微分\n",
    "        self.dW = None\n",
    "        self.db = None\n",
    "\n",
    "    def forward(self, x):\n",
    "        # テンソル対応\n",
    "        self.original_x_shape = x.shape\n",
    "        x = x.reshape(x.shape[0], -1)\n",
    "        self.x = x\n",
    "\n",
    "        out = np.dot(self.x, self.W) + self.b\n",
    "\n",
    "        return out\n",
    "\n",
    "    def backward(self, dout):\n",
    "        dx = np.dot(dout, self.W.T)\n",
    "        self.dW = np.dot(self.x.T, dout)\n",
    "        self.db = np.sum(dout, axis=0)\n",
    "        \n",
    "        dx = dx.reshape(*self.original_x_shape)  # 入力データの形状に戻す（テンソル対応）\n",
    "        return dx\n",
    "\n",
    "\n",
    "class SoftmaxWithLoss:\n",
    "    def __init__(self):\n",
    "        self.loss = None\n",
    "        self.y = None # softmaxの出力\n",
    "        self.t = None # 教師データ\n",
    "\n",
    "    def forward(self, x, t):\n",
    "        self.t = t\n",
    "        self.y = softmax(x)\n",
    "        self.loss = cross_entropy_error(self.y, self.t)\n",
    "        \n",
    "        return self.loss\n",
    "\n",
    "    def backward(self, dout=1):\n",
    "        batch_size = self.t.shape[0]\n",
    "        if self.t.size == self.y.size: # 教師データがone-hot-vectorの場合\n",
    "            dx = (self.y - self.t) / batch_size\n",
    "        else:\n",
    "            dx = self.y.copy()\n",
    "            dx[np.arange(batch_size), self.t] -= 1\n",
    "            dx = dx / batch_size\n",
    "        \n",
    "        return dx\n",
    "\n",
    "\n",
    "class Dropout:\n",
    "    \"\"\"\n",
    "    http://arxiv.org/abs/1207.0580\n",
    "    \"\"\"\n",
    "    def __init__(self, dropout_ratio=0.5):\n",
    "        self.dropout_ratio = dropout_ratio\n",
    "        self.mask = None\n",
    "\n",
    "    def forward(self, x, train_flg=True):\n",
    "        if train_flg:\n",
    "            self.mask = np.random.rand(*x.shape) > self.dropout_ratio\n",
    "            return x * self.mask\n",
    "        else:\n",
    "            return x * (1.0 - self.dropout_ratio)\n",
    "\n",
    "    def backward(self, dout):\n",
    "        return dout * self.mask\n",
    "\n",
    "\n",
    "class BatchNormalization:\n",
    "    \"\"\"\n",
    "    http://arxiv.org/abs/1502.03167\n",
    "    \"\"\"\n",
    "    def __init__(self, gamma, beta, momentum=0.9, running_mean=None, running_var=None):\n",
    "        self.gamma = gamma\n",
    "        self.beta = beta\n",
    "        self.momentum = momentum\n",
    "        self.input_shape = None # Conv層の場合は4次元、全結合層の場合は2次元  \n",
    "\n",
    "        # テスト時に使用する平均と分散\n",
    "        self.running_mean = running_mean\n",
    "        self.running_var = running_var  \n",
    "        \n",
    "        # backward時に使用する中間データ\n",
    "        self.batch_size = None\n",
    "        self.xc = None\n",
    "        self.std = None\n",
    "        self.dgamma = None\n",
    "        self.dbeta = None\n",
    "\n",
    "    def forward(self, x, train_flg=True):\n",
    "        self.input_shape = x.shape\n",
    "        if x.ndim != 2:\n",
    "            N, C, H, W = x.shape\n",
    "            x = x.reshape(N, -1)\n",
    "\n",
    "        out = self.__forward(x, train_flg)\n",
    "        \n",
    "        return out.reshape(*self.input_shape)\n",
    "            \n",
    "    def __forward(self, x, train_flg):\n",
    "        if self.running_mean is None:\n",
    "            N, D = x.shape\n",
    "            self.running_mean = np.zeros(D)\n",
    "            self.running_var = np.zeros(D)\n",
    "                        \n",
    "        if train_flg:\n",
    "            mu = x.mean(axis=0)\n",
    "            xc = x - mu\n",
    "            var = np.mean(xc**2, axis=0)\n",
    "            std = np.sqrt(var + 10e-7)\n",
    "            xn = xc / std\n",
    "            \n",
    "            self.batch_size = x.shape[0]\n",
    "            self.xc = xc\n",
    "            self.xn = xn\n",
    "            self.std = std\n",
    "            self.running_mean = self.momentum * self.running_mean + (1-self.momentum) * mu\n",
    "            self.running_var = self.momentum * self.running_var + (1-self.momentum) * var            \n",
    "        else:\n",
    "            xc = x - self.running_mean\n",
    "            xn = xc / ((np.sqrt(self.running_var + 10e-7)))\n",
    "            \n",
    "        out = self.gamma * xn + self.beta \n",
    "        return out\n",
    "\n",
    "    def backward(self, dout):\n",
    "        if dout.ndim != 2:\n",
    "            N, C, H, W = dout.shape\n",
    "            dout = dout.reshape(N, -1)\n",
    "\n",
    "        dx = self.__backward(dout)\n",
    "\n",
    "        dx = dx.reshape(*self.input_shape)\n",
    "        return dx\n",
    "\n",
    "    def __backward(self, dout):\n",
    "        dbeta = dout.sum(axis=0)\n",
    "        dgamma = np.sum(self.xn * dout, axis=0)\n",
    "        dxn = self.gamma * dout\n",
    "        dxc = dxn / self.std\n",
    "        dstd = -np.sum((dxn * self.xc) / (self.std * self.std), axis=0)\n",
    "        dvar = 0.5 * dstd / self.std\n",
    "        dxc += (2.0 / self.batch_size) * self.xc * dvar\n",
    "        dmu = np.sum(dxc, axis=0)\n",
    "        dx = dxc - dmu / self.batch_size\n",
    "        \n",
    "        self.dgamma = dgamma\n",
    "        self.dbeta = dbeta\n",
    "        \n",
    "        return dx\n",
    "\n",
    "\n",
    "class Convolution:\n",
    "    def __init__(self, W, b, stride=1, pad=0):\n",
    "        self.W = W\n",
    "        self.b = b\n",
    "        self.stride = stride\n",
    "        self.pad = pad\n",
    "        \n",
    "        # 中間データ（backward時に使用）\n",
    "        self.x = None   \n",
    "        self.col = None\n",
    "        self.col_W = None\n",
    "        \n",
    "        # 重み・バイアスパラメータの勾配\n",
    "        self.dW = None\n",
    "        self.db = None\n",
    "\n",
    "    def forward(self, x):\n",
    "        FN, C, FH, FW = self.W.shape\n",
    "        N, C, H, W = x.shape\n",
    "        out_h = 1 + int((H + 2*self.pad - FH) / self.stride)\n",
    "        out_w = 1 + int((W + 2*self.pad - FW) / self.stride)\n",
    "\n",
    "        col = im2col(x, FH, FW, self.stride, self.pad)\n",
    "        col_W = self.W.reshape(FN, -1).T\n",
    "\n",
    "        out = np.dot(col, col_W) + self.b\n",
    "        out = out.reshape(N, out_h, out_w, -1).transpose(0, 3, 1, 2)\n",
    "\n",
    "        self.x = x\n",
    "        self.col = col\n",
    "        self.col_W = col_W\n",
    "\n",
    "        return out\n",
    "\n",
    "    def backward(self, dout):\n",
    "        FN, C, FH, FW = self.W.shape\n",
    "        dout = dout.transpose(0,2,3,1).reshape(-1, FN)\n",
    "\n",
    "        self.db = np.sum(dout, axis=0)\n",
    "        self.dW = np.dot(self.col.T, dout)\n",
    "        self.dW = self.dW.transpose(1, 0).reshape(FN, C, FH, FW)\n",
    "\n",
    "        dcol = np.dot(dout, self.col_W.T)\n",
    "        dx = col2im(dcol, self.x.shape, FH, FW, self.stride, self.pad)\n",
    "\n",
    "        return dx\n",
    "\n",
    "\n",
    "class Pooling:\n",
    "    def __init__(self, pool_h, pool_w, stride=1, pad=0):\n",
    "        self.pool_h = pool_h\n",
    "        self.pool_w = pool_w\n",
    "        self.stride = stride\n",
    "        self.pad = pad\n",
    "        \n",
    "        self.x = None\n",
    "        self.arg_max = None\n",
    "\n",
    "    def forward(self, x):\n",
    "        N, C, H, W = x.shape\n",
    "        out_h = int(1 + (H - self.pool_h) / self.stride)\n",
    "        out_w = int(1 + (W - self.pool_w) / self.stride)\n",
    "\n",
    "        col = im2col(x, self.pool_h, self.pool_w, self.stride, self.pad)\n",
    "        col = col.reshape(-1, self.pool_h*self.pool_w)\n",
    "\n",
    "        arg_max = np.argmax(col, axis=1)\n",
    "        out = np.max(col, axis=1)\n",
    "        out = out.reshape(N, out_h, out_w, C).transpose(0, 3, 1, 2)\n",
    "\n",
    "        self.x = x\n",
    "        self.arg_max = arg_max\n",
    "\n",
    "        return out\n",
    "\n",
    "    def backward(self, dout):\n",
    "        dout = dout.transpose(0, 2, 3, 1)\n",
    "        \n",
    "        pool_size = self.pool_h * self.pool_w\n",
    "        dmax = np.zeros((dout.size, pool_size))\n",
    "        dmax[np.arange(self.arg_max.size), self.arg_max.flatten()] = dout.flatten()\n",
    "        dmax = dmax.reshape(dout.shape + (pool_size,)) \n",
    "        \n",
    "        dcol = dmax.reshape(dmax.shape[0] * dmax.shape[1] * dmax.shape[2], -1)\n",
    "        dx = col2im(dcol, self.x.shape, self.pool_h, self.pool_w, self.stride, self.pad)\n",
    "        \n",
    "        return dx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from deep_learning_from_scratch.common.gradient import numerical_gradient\n",
    "from collections import OrderedDict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class TwoLayerNet:\n",
    "\n",
    "    def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):\n",
    "        # 重みの初期化\n",
    "        self.params = {}\n",
    "        self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)\n",
    "        self.params['b1'] = np.zeros(hidden_size)\n",
    "        self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)\n",
    "        self.params['b2'] = np.zeros(output_size)\n",
    "        \n",
    "        # レイヤの生成\n",
    "        self.layers = OrderedDict()\n",
    "        self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])\n",
    "        self.layers['Relu1'] = Relu()\n",
    "        self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])\n",
    "        self.lastLayer = SoftmaxWithLoss()        \n",
    "\n",
    "    def predict(self, x):\n",
    "        for layer in sel.layers.values():\n",
    "            x = layer.forward(x)\n",
    "        return x\n",
    "        \n",
    "    # x:入力データ, t:教師データ\n",
    "    def loss(self, x, t):\n",
    "        y = self.predict(x)\n",
    "        return cross_entropy_error(y, t)\n",
    "    \n",
    "    def accuracy(self, x, t):\n",
    "        y = self.predict(x)\n",
    "        y = np.argmax(y, axis=1)\n",
    "        if t.ndim != 1: t = np.argmax(t, axis=1)\n",
    "        \n",
    "        accuracy = np.sum(y == t) / float(x.shape[0])\n",
    "        return accuracy\n",
    "    \n",
    "    # x:入力データ, t:教師データ\n",
    "    def numerical_gradient(self, x, t):\n",
    "        loss_W = lambda W: self.loss(x, t)\n",
    "        \n",
    "        grads = {}\n",
    "        grads['W1'] = numerical_gradient(loss_W, self.params['W1'])\n",
    "        grads['b1'] = numerical_gradient(loss_W, self.params['b1'])\n",
    "        grads['W2'] = numerical_gradient(loss_W, self.params['W2'])\n",
    "        grads['b2'] = numerical_gradient(loss_W, self.params['b2'])\n",
    "        \n",
    "        return grads\n",
    "        \n",
    "    def gradient(self, x, t):        \n",
    "        # forward\n",
    "        self.loss(x, t)\n",
    "        \n",
    "        # backward\n",
    "        dout = 1\n",
    "        dout = self.lastLayer.backward(dout)\n",
    "        \n",
    "        layers = list(self.layers.values())\n",
    "        layser.reverse()\n",
    "        for layer in layers:\n",
    "            dout = layer.backward(dout)\n",
    "        \n",
    "        # 設定\n",
    "        grads['W1'] = self.layers['Affine1'].dW\n",
    "        grads['b1'] = self.layers['Affine1'].db\n",
    "        grads['W2'] = self.layers['Affine2'].dW\n",
    "        grads['b2'] = self.layers['Affine2'].db\n",
    "\n",
    "        return grads"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cd deep_learning_from_scratch/ch05 && python3 gradient_check.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cd deep_learning_from_scratch/ch05 && python3 train_neuralnet.py"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
